# -*- encoding: utf-8 -*-
from django.template import RequestContext
from django.shortcuts import render_to_response, get_object_or_404
from django.contrib.auth.decorators import user_passes_test
from django.http import HttpResponseRedirect
from django.views.decorators.cache import cache_page

from models import Sponsor

@cache_page(60 * 15)
def sponsors(request):
    sponsors = request.section.sponsors.order_by('order')

    return render_to_response('sponsors/sponsors.html',
                              {'sponsors': sponsors,},
                              context_instance=RequestContext(request))

@user_passes_test(lambda u: u.is_superuser)
def changeSponsorOrder(request):

    sponsors = Sponsor.objects.order_by('order')

    i = 1
    for s in sponsors:
        s.order = i
        s.save()
        i += 1

    if request.method == "POST":
        if request.POST['sponsors'] == 'order':
            for s in sponsors:
                if s.order != request.POST[str(s.order)]:
                    s.order = request.POST[str(s.order)]
                    s.save()

            return HttpResponseRedirect(request.path)
  
    return render_to_response('admin/changeSponsorOrder.html', {'sponsors': sponsors},
                              context_instance=RequestContext(request))
